package com.cz.video.common.vod.config;

import cn.hutool.core.collection.CollUtil;
import com.cz.video.common.storage.hander.AliyunStsHandler;
import com.cz.video.common.vod.AliyunVod;
import com.cz.video.common.vod.VodProvider;
import com.cz.video.common.vod.service.VodService;
import com.cz.video.common.vod.properties.VodProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

@Slf4j
@Configuration
@AutoConfiguration
@RequiredArgsConstructor
@EnableConfigurationProperties(VodProperties.class)
public class VodConfiguration implements WebMvcConfigurer {

    private final VodProperties properties;
    private final ApplicationContext applicationContext;


    /**
     * 阿里云 Vod  Bean
     */
    @Bean
    @ConditionalOnClass(name = "com.aliyuncs.vod.Endpoint")
    public List<AliyunVod> aliyunVodList() {
        return properties.getAliyunVod().stream().map(vodProperties -> {
            if (!vodProperties.getEnableVod()) return null;
            log.info("加载vodProperties平台：{}",vodProperties.getPlatform());
            AliyunVod vod = new AliyunVod();
            AliyunStsHandler handler = new AliyunStsHandler();
            //设置vod
            vod.setPlatform(vodProperties.getPlatform());
            vod.setAccessKey(vodProperties.getAccessKey());
            vod.setSecretKey(vodProperties.getSecretKey());
            vod.setEnableSts(vodProperties.getEnableSts());
            vod.setCallbackURL(vodProperties.getCallbackUrl());
            vod.setRegionId(vodProperties.getRegionId());
            vod.setPlayAuthTimeOut(vodProperties.getPlayAuthTimeOut());
            vod.setEnableCallBackAuthentication(vodProperties.getEnableCallBackAuthentication());
            vod.setAuthKey(vodProperties.getAuthKey());

            //设置handler
            if (vodProperties.getEnableSts()){
                handler.setStsAccessKey(vodProperties.getStsAccessKey());
                handler.setStsAccessSecret(vodProperties.getStsAccessSecret());
                handler.setArn(vodProperties.getArn());
                handler.setStsEndpoint(vodProperties.getStsEndpoint());
                handler.setStsDuration(vodProperties.getStsDuration());
                handler.setRegionId(vodProperties.getRegionId());

                vod.setStsHandler(handler);
            }
            return vod;
        }).filter(Objects::nonNull).collect(Collectors.toList());
    }



    /**
     * 文件存储服务
     */
    @Bean
    public VodService vodService(List<List<? extends VodProvider>> vodLists
                                                 ) {
        this.initDetect();
        VodService service = new VodService();
        //设置vod
        service.setVodList(new CopyOnWriteArrayList<>());
        vodLists.forEach(service.getVodList()::addAll);

        service.setProperties(properties);
        return service;
    }

    /**
     * 对 VodService 注入自己的代理对象，不然会导致针对 VodService 的代理方法不生效
     */
    @EventListener(ContextRefreshedEvent.class)
    public void onContextRefreshedEvent() {
        VodService service = applicationContext.getBean(VodService.class);
        service.setSelf(service);
    }

    //  初始化检测
    public void initDetect() {
        String template = "检测到{}配置，但是没有找到对应的依赖库，所以无法加载此vod平台！";

        if (CollUtil.isNotEmpty(properties.getAliyunVod()) && doesNotExistClass("com.aliyuncs.vod.Endpoint")) {
            log.warn(template,"阿里云 OSS ");
        }

    }

    /**
     * 判断是否没有引入指定 Class
     */
    public static boolean doesNotExistClass(String name) {
        try {
            Class.forName(name);
            return false;
        } catch (ClassNotFoundException e) {
            return true;
        }
    }

}
